import { BrowserWindow, remote } from "electron";
import path from "path";
import { isLinux } from "@anyshare/common/lib/utils/platform";
export class BlankWindow {
    private readonly _win: BrowserWindow;
    private readonly _id: number;
    private _isReady: boolean;
    private readonly whenReadyCallbacks: {
        (window: BlankWindow): void;
    }[];

    constructor() {
        this._isReady = false;
        this._win = new remote.BrowserWindow({
            show: false,
            frame: false,
            hasShadow: true,
            center: true,
            icon: isLinux ? path.resolve(remote.app.getAppPath(), "./resources/common/icon.png") : undefined,
            webPreferences: {
                devTools: true,
                nodeIntegration: true,
                nodeIntegrationInWorker: true,
                webSecurity: false,
                enableRemoteModule: true,
                webviewTag: true,
            },
        });
        this._id = this._win.id;
        this._win.loadURL(
            `${window.location.protocol}${window.location.host}${window.location.pathname}#/anyshare/_blank`
        );
        this.whenReadyCallbacks = [];
    }

    public get id() {
        return this._id;
    }

    public get win() {
        return this._win;
    }

    public get isReady() {
        return this._isReady;
    }

    public ready(): Promise<BlankWindow> {
        return new Promise<BlankWindow>((resolve) => {
            if (this.isReady) {
                return resolve(this);
            }
            this.whenReadyCallbacks.push(resolve);
        });
    }

    public setReady() {
        this._isReady = true;
        while (this.whenReadyCallbacks.length) {
            this.whenReadyCallbacks.pop()!(this);
        }
    }

    public send(channel: string, ...args: any[]) {
        if (this._win && !this._win.isDestroyed()) {
            this._win.webContents.send(channel, ...args);
        }
    }

    public sendWhenReady(channel: string, ...args: any[]) {
        if (this.isReady) {
            this.send(channel, ...args);
        } else {
            this.ready().then(() => this.send(channel, ...args));
        }
    }
}
